/*
* @Author: Administrator
* @Date:   2018-01-05 08:39:35
* @Last Modified by:   Administrator
* @Last Modified time: 2018-01-06 09:28:07
*/
import { observable, action, toJS, computed } from 'mobx'
import userLogin from '../request/user_login';
import userLogout from '../request/user_logout';
import userRegist from '../request/user_regist';

class User {
  constructor(userInfo) {
    if (userInfo.user_id) {
      this.userInfo = userInfo
    } else {
      this.userInfo = {}
    }
  }
  @observable userInfo
  @observable isLoging = false
  @observable errors = ''
  @action login(userParm) {
    this.isLoging = true
    this.errors = ''
    return new Promise((resolve, reject) => {
      userLogin(userParm).then((res) => {
        if (res.status === 200 && res.data.user_id) {
          this.userInfo = res.data
          resolve()
        } else if (res.status === 200 && res.data.code === 0) {
          this.errors = res.data.message
          reject()
        } else {
          reject(res.data)
        }
        this.isLoging = false
      }).catch(reject)
    })
  }
  @action logout() {
    return new Promise((resolve, reject) => {
      userLogout().then((res) => {
        if (res.status === 200 && res.data.code === 1) {
          this.userInfo = {}
          resolve()
        } else {
          reject(res.data)
        }
        this.isLoging = false
      }).catch(reject)
    })
  }
  @action regist(param) {
    return new Promise((resolve, reject) => {
      userRegist(param).then((res) => {
        if (res.status === 200) {
          resolve(res.data)
        } else {
          reject(res.data)
        }
      }).catch(reject)
    })
  }
  @computed get isLogined() {
    return !!this.userInfo.user_id
  }
  toJson() {
    return {
      userInfo: toJS(this.userInfo),
    }
  }
}
export default User
